import io, re, sys
p = r'app/api/production.py'
s = io.open(p, 'r', encoding='utf-8').read()
# locate function get_production_order_detail
mfun = re.search(r"def\s+get_production_order_detail\s*\(\)\s*:\n", s)
if not mfun:
    print('FUNC_NOT_FOUND'); sys.exit(0)
start_fun = mfun.end()
# find start and end markers
m_start = re.search(r"order_id\s*=\s*request\.args\.get\('order_id'\)", s[start_fun:])
if not m_start:
    print('START_NOT_FOUND'); sys.exit(0)
abs_start = start_fun + m_start.start()
# find next logger.info within function
m_end = re.search(r"logger\.info\(f?\"", s[abs_start:])
if not m_end:
    print('END_NOT_FOUND'); sys.exit(0)
abs_end = abs_start + m_end.start()
new_block = (
    "        # Accept multiple parameter names to match YonBIP: id, order_id, code\n"
    "        order_id = request.args.get('order_id')\n"
    "        legacy_id = request.args.get('id')\n"
    "        code = request.args.get('code')\n\n"
    "        if not (order_id or legacy_id or code):\n"
    "            return error_response(\"订单ID不能为空\", code=\"400\"), 400\n\n"
    "        # Normalize to internal format: ORDxxxx\n"
    "        if not order_id:\n"
    "            import re\n"
    "            if legacy_id and str(legacy_id).isdigit():\n"
    "                n = int(legacy_id)\n"
    "                order_num = (n % 9999) + 1\n"
    "                order_id = f\"ORD{order_num:04d}\"\n"
    "            elif code:\n"
    "                m = re.search(r'(\\d+)$', code)\n"
    "                num = int(m.group(1)) if m else 1\n"
    "                order_num = (num % 9999) + 1\n"
    "                order_id = f\"ORD{order_num:04d}\"\n"
    "            else:\n"
    "                return error_response(\"订单ID不能为空\", code=\"400\"), 400\n\n"
)
s2 = s[:abs_start] + new_block + s[abs_end:]
io.open(p, 'w', encoding='utf-8', newline='\n').write(s2)
print('OK')
